<?php
/**商品管理
 * @Author: 976123967@qq.com
 * @Date:   2014-08-31 16:42:35
 * @Last Modified by:   chen
 * @Last Modified time: 2014-08-31 23:47:23
 */
class GoodsControl extends CommonControl{

	private $goodsDetailModel;
	/**
	 * [__auto 初始化]
	 * @return [type] [description]
	 */
	public function __auto()
	{
		$this->model = K('Goods');
		$this->goodsDetailModel = K('GoodsDetail');
		$this->assign('shopname',K('Shop')->where(array('shopid',Q('get.shopid')))->getField('shopname'));

	}


	/**
	 * [index 所有商品]
	 * @return [type] [description]
	 */
	public function index()
	{
		$db = K('GoodsView');

		// 查询条件
		$shopid = Q('get.shopid',null,'intval');
		$where[C('DB_PREFIX').'shop.shopid'] = $shopid;


		$count = $db->where($where)->count();
		$page = new Page($count,20);
		$goods = $db->get_goods_all($where,$page->limit());
		$this->assign('page',$page->show());
		$this->assign('goods',$goods);


		$this->display();
	}


	/**
	 * [add 添加]
	 */
	public function add()
	{

		if(IS_POST)
		{

			if(!$this->model->create()) $this->error($this->model->error);
			$gid = $this->model->add_goods();
			$this->goodsDetailModel->add_goods_detail($gid);
			$this->success('商品添加成功',U('Goods/index',array('shopid'=>Q('post.shopid'))));
		}



		$this->assign('category',K('Category')->get_category_all());
		$this->assign('city',K('City')->get_city_all());
		$this->assign('shop',K('Shop')->get_shop_all());
		$this->assign('goodsServer',C('goodsServer'));

		$this->display();
	}


	/**
	 * [edit 编辑]
	 * @return [type] [description]
	 */
	public function edit()
	{


		if(IS_POST)
		{
			if(!$this->model->create()) $this->error($this->model->error);
			$this->model->edit_goods();
			$gid = Q('post.gid',0,'intval');
			$this->goodsDetailModel->edit_goods_detail($gid);
			$this->success('商品编辑成功',U('Goods/index',array('shopid'=>Q('post.shopid'))));
		}



		$gid = Q('get.gid',0,'intval');

		$data = K('GoodsView')->get_goods_one($gid);
		if(!$data) $this->error('商品不存在');
		$this->assign('data',$data);


		$this->assign('category',K('Category')->get_category_all());
		$this->assign('city',K('City')->get_city_all());
		$this->assign('shop',K('Shop')->get_shop_all());
		$this->assign('goodsServer',C('goodsServer'));

		$this->display();
	}




	/**
	 * [del_goods 删除]
	 * @return [type] [description]
	 */
	public function del()
	{
		$gid = Q('get.gid',0,'intval');
		$data = K('GoodsView')->get_goods_one($gid);
		if(!$data) $this->error('商品不存在');
 		$this->model->del_goods($gid);
		$this->goodsDetailModel->del_goods_detail($gid);
		$this->success('商品删除成功',U('Goods/index',array('shopid'=>$data['shopid'])));
	}

}